<template>
  <div class="recharge">
    <transition name="fade">
      <div class="do-recharge"
           v-if="!rechargeStatus || Object.keys(rechargeStatus).length === 0"
      >
        <div class="recharge__tabs" v-if="show && largeMerchant">
          <div class="recharge__tabs-item" :class="{active: form.limitType === 0}" @click="changeTabs(0)">普通充值</div>
          <div class="recharge__tabs-line"></div>
          <div class="recharge__tabs-item" :class="{active: form.limitType === 1}" @click="changeTabs(1)">大额快速充值</div>
        </div>
        <div v-show="step === 1">
        <el-form :model="form" :rules="refRules" ref="amountForm" label-position="top"
                 :disabled="loading"
                 @submit.native.prevent="goNext">
            <el-form-item label="账户余额：" class="recharge__center-amount">
              &yen; {{fBalance}}
            </el-form-item>
            <el-form-item label="快速充值：" class="recharge__quick">
              <div class="recharge__quick-group">
                <template v-for="item in fastAmountList">
                  <el-button
                    :key="item"
                    class="recharge__quick-button"
                    size="medium"
                    :type="form.amount == item ? 'primary' : 'outline-info'"
                    @click="selectMoney(item)">
                    {{item}}元
                  </el-button>
                </template>

              </div>
            </el-form-item>
            <el-form-item prop="amount" class="recharge__amount" :error="formError">
              <el-input placeholder="充值金额" type="text" v-model.number="form.amount" maxlength="18">
                <template slot="prepend">
                  <svg-icon class="finance-modal__svg-prepend" icon-class="withdraw"></svg-icon>
                </template>
                <template slot="append"><span class="text-black">CNY</span></template>
              </el-input>
            </el-form-item>
            <el-button type="primary recharge__next-btn" native-type="submit" block :loading="btnLoading">下一步</el-button>
        </el-form>
        </div>
        <div v-show="step === 2">
          <el-form :model="form" :rules="refRules" ref="form" label-position="top"
                     :disabled="loading"
                     @submit.native.prevent="doRechargeNow">
            <div class="recharge__to-amount">待充值：&yen; {{form.amount}}</div>
            <el-form-item label="选择充值方式：" prop="paymentId">
              <el-select v-model="form.paymentId" placeholder="请选择支付方式" @change="getPaymentInfo" block>
                <template slot="prefix">
                  <payment-pic :payment-id="form.paymentId"></payment-pic>
                </template>
                <el-option v-for="item in rechargeList"
                           class="finance-modal__payment-option"
                           :key="item.paymentId"
                           :label="item.paymentName"
                           :value="item.paymentId">
                  <payment-pic :payment-id="item.paymentId"></payment-pic>
                  {{item.paymentName}}
                </el-option>
              </el-select>
            </el-form-item>

            <el-form-item prop="cardNo" key="cardNo" label="银行卡号："
                          v-if="[24].indexOf(form.paymentId) !== -1 && needCardNo">
              <el-autocomplete
                      block
                      class="recharge__card_no"
                      v-model="form.cardNo"
                      :fetch-suggestions="queryCardSearch"
                      placeholder="请输入银行卡号"
                      @select="handleSelect"
              >
                <template slot="prepend">
                  <svg-icon class="finance-modal__svg-prepend" icon-class="card-receive"></svg-icon>
                </template>
              </el-autocomplete>
            </el-form-item>

            <el-form-item prop="bankId" key="bankId" label="支付银行：" v-if="[1, 7, 17].indexOf(form.paymentId) !== -1">
              <el-select
                      v-model="form.bankId"
                      @change="getBankCode"
                      block
              >
                <template slot="prefix">
                  <bank-pic :bank-id="form.bankId"></bank-pic>
                </template>
                <el-option v-for="item in bankList"
                           class="finance-modal__bank-option"
                           :key="item.bankId"
                           :label="item.bankName"
                           :value="item.bankId">
                  <bank-pic :bank-id="item.bankId"></bank-pic>
                  {{item.bankName}}
                </el-option>
              </el-select>
            </el-form-item>

            <el-form-item prop="name" key="aliName" label="支付宝姓名："
                          v-if="[consts.PAY_ZHIFUBAO_ZHUANZ].indexOf(form.paymentId) !== -1 && needName">
              <el-autocomplete
                      block
                      class="recharge__card_no"
                      v-model.trim="form.name"
                      :fetch-suggestions="queryNameSearch"
                      placeholder="请输入支付宝姓名"
                      @select="handleSelect"
              >
                <template slot="prepend">
                  <svg-icon class="finance-modal__svg-prepend" icon-class="user-circle"></svg-icon>
                </template>
              </el-autocomplete>
              <el-warning class="text-danger">请与实际付款账户姓名保持一致，否则影响到帐</el-warning>
            </el-form-item>

            <el-form-item prop="name" key="aliName" label="银行卡姓名："
                          v-if="[consts.PAY_BANKCARD_ZHUANZ].indexOf(form.paymentId) !== -1 && needName">
              <el-autocomplete
                      block
                      class="recharge__card_no"
                      v-model.trim="form.name"
                      :fetch-suggestions="queryNameSearch"
                      placeholder="请输入银行卡姓名"
                      @select="handleSelect"
              >
                <template slot="prepend">
                  <svg-icon class="finance-modal__svg-prepend" icon-class="user-circle"></svg-icon>
                </template>
              </el-autocomplete>
              <el-warning class="text-danger">请与实际付款账户姓名保持一致，否则影响到帐</el-warning>
            </el-form-item>
  
            <el-form-item label="选择支付通道：" prop="merchantAppId" v-if="showMerchant">
              <el-select v-model="form.merchantAppId" @change="checkLimitTip" placeholder="请选择支付通道" block>
                <el-option v-for="item in merchantList"
                           class="finance-modal__payment-option recharge__payment-option"
                           :key="item.appId"
                           :label="formatMerchantName(item)"
                           :value="item.appId">
                  <span>{{formatMerchantName(item)}}</span>
                  <span class="text-danger" v-if="item.recommendStatus === 0">（推荐）</span>
                </el-option>
              </el-select>
              <div v-if="showlimitTip" class="recharge__merchantAppId-limit text-danger">（推荐）</div>
            </el-form-item>
            <div class="recharge__fee" :class="{'fee-top': !showMerchant}" v-if="selectMerchantList && feeAmount > 0">
              <div class="recharge__fee-block" v-if="selectMerchantList.fee">
                手续费金额：<span class="text-normal">{{feeAmount | currency}}元</span>
              </div>
              {{selectMerchantList.fee ? '实际' : ''}}到账金额：<span
              class="text-normal">{{actual?actual:0 | currency}}元</span>
            </div>

            <el-button type="primary" native-type="submit" block :loading="btnLoading">下一步</el-button>
          </el-form>
        </div>
        <!--<div class="recharge__tip">-->
          <!--<router-link tag="div" class="recharge__tip-faq"-->
                       <!--:to="{name: 'about-us', params: {path: 'deposit'}}"-->
                       <!--@click.native="closeCharge"-->
          <!--&gt;-->
            <!--<svg-icon icon-class="faq" type="info"></svg-icon>-->
            <!--充值流程如何进行？-->
          <!--</router-link>-->
        <!--</div>-->
      </div>
      <recharge-status
              :recharge-status="rechargeStatus"
              @refresh-status="refreshStatus"
              @on-cancel="rechargeStatus = undefined"
              v-else
      ></recharge-status>
    </transition>
  </div>
</template>

<script>
  import {getLogin} from '@/utils/auth';
  import {factory, form, capitalOperation} from '@/build';
  import {
    getRechargePaymentInfoApi,
    getRechargeStatus,
    rechargeTransfer,
    getRechargeFastAmount
  } from '@/services/api/finance';
  
  import RechargeStatus from './recharge-status';
  
  import localBankList from '../bank-config';
  // import RechargeSwiper from "@/views/finance/recharge/recharge-swiper";
  
  export default {
    name: "finance-recharge",
    
    components: {
      // RechargeSwiper,
      RechargeStatus
    },
    
    mixins: [form, factory, capitalOperation],
    
    data() {
      return {
        show: true,
        rechargeList: [],
        cardList: [],
        nameList: [],
        form: {
          amount: undefined,
          paymentId: undefined,
          bankId: undefined,
          name: undefined,
          cardNo: undefined,
          limitType: 0,
          merchantAppId:undefined,
          appType:0,
        },
        formError: '',
        rechargeWait: false,
        fakeAmount: 0,
        needCardNo: false,
        needName: false,
        innerPay: false,
        refRules: {
          paymentId: {required: true, message: '充值方式为必选项'},
          bankId: {required: true, message: '银行为必选项'},
          cardNo: factory.getRule('cardNumber'),
          name: [
            {required: true, message: '姓名不能为空'},
            // {pattern: /^[\u4E00-\u9FA5]+$/, message: '姓名只能为中文', trigger: 'blur'}
          ],
          amount: [
            ...factory.getRule('money')
          ],
          merchantAppId:{required: true, message: '充值通道为必选项'},
        },
        rechargeStatus: undefined,
        step:1,
        btnLoading:false,
        fastAmount:[],
        merchantList:[],
        showlimitTip:false,
        showMerchant: false,
        largeMerchant: false,
      };
    },
    
    watch: {
      form: {
        handler(newValue, oldValue) {
          if (this.rechargeList != undefined && this.rechargeList !== []) {
            let payment = _.find(this.rechargeList, item => {
              return item.paymentId === newValue.paymentId;
            });
            if (payment) {
              const { merchantList } = payment;
              if(merchantList){
                const nowMerchantInfo = _.find(merchantList,{appId: this.form.merchantAppId});
                this.innerPay = nowMerchantInfo.innerPay;
                if(nowMerchantInfo.cardList && nowMerchantInfo.cardList.length > 0){
                  this.cardList = nowMerchantInfo.cardList.map(item => {
                    return {value: item};
                  });
                }else{
                  this.cardList = [];
                }
                if(nowMerchantInfo.nameList && nowMerchantInfo.nameList.length > 0){
                  this.nameList = _.map(nowMerchantInfo.nameList, item => {
                    return {
                      value: item
                    };
                  });
                }else{
                  this.nameList = [];
                }
                this.needCardNo = nowMerchantInfo.needCardNo;
                this.needName = nowMerchantInfo.needName;
                this.showlimitTip = nowMerchantInfo.recommendStatus === 0 ? true : false;
              }
            }
          }
        },
        deep: true
      },
    },
    
    computed: {
      selectMerchantList() {  //当前选中的支付通道
        return _.find(this.merchantList,{appId: this.form.merchantAppId});
      },
      amount() {
        if (!_.isUndefined(this.form.amount)) {
          return this.form.amount.toFixed(2);
        }
      },
      feeAmount() {
        let fee = parseInt(this.form.amount) * this.selectMerchantList.fee / 100;
        fee = fee > this.selectMerchantList.feeLimit ? this.selectMerchantList.feeLimit : fee;
        return fee.toFixed(2);
      },
      actual() {
        return parseInt(this.form.amount) - this.feeAmount;
      },
      bankList() {
        return this.form.paymentId === 7 ? localBankList : (this.selectMerchantList ? this.selectMerchantList.bankList : []);
      },
      
      fastAmountList() {
        return this.form.limitType === 0 ? this.fastAmount.common : this.fastAmount.large;
      },
      ...mapState({
        user: state => state.user
      }),
      ...mapGetters([
        'fBalance'
      ])
    },
    
    methods: {
      changeTabs(type){
        this.form.limitType = type;
        this.step = 1;
        // this.typeChange();
        this.$refs['form'].resetFields();
      },
      goNext(){
        this.$refs['amountForm'].validate((valid) => {
          if (valid) {
            this.btnLoading = true;
            this.doSave({action: 'paymentInfo'});
          }
        });
      },
      formatMerchantName(item){
        let limit = '';
        if(item.maxAmount > 0) {
          limit = `（限额${item.minAmount}~${item.maxAmount}）`;
        }
        return item.aisleName + limit;
      },
      checkLimitTip(data){
        const info = this.merchantList.find(item => item.appId === data);
        this.showlimitTip = info.recommendStatus === 0 ? true : false;
      },
      queryCardSearch(queryString, cb) {
        var cardList = this.cardList;
        var results = queryString ? cardList.filter(this.createFilter(queryString)) : cardList;
        // 调用 callback 返回建议列表的数据
        cb(results);
      },
      queryNameSearch(queryString, cb) {
        var nameList = this.nameList;
        var results = queryString ? nameList.filter(this.createFilter(queryString)) : nameList;
        // 调用 callback 返回建议列表的数据
        cb(results);
      },
      createFilter(queryString) {
        return (list) => {
          return (list.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0);
        };
      },
      handleSelect(item) {
        console.log(item);
      },
      initForm() {
        this.step = 1;
        const rechargeList = JSON.parse(window.localStorage.getItem('rechargeList'));
        if (rechargeList) {
          this.form = {
            amount: undefined,
            paymentId: rechargeList[0].paymentId,
            bankId: undefined,
            merchantAppId: rechargeList[0].merchantList[0].appId,
            name: undefined,
            limitType: 0,
            appType:2,
          };
        }
      },
      selectMoney(money) {
        this.form.amount = money;
      },
      getPaymentInfo(paymentId) {
        this.merchantList = _.find(this.rechargeList,{paymentId}).merchantList;
        this.form.merchantAppId = this.merchantList[0].appId;
        this.showlimitTip = this.merchantList[0] === 0 ? true : false;
        if(paymentId === 1 && this.merchantList[0].bankList.length > 0){
          this.form.bankId = this.merchantList[0].bankList[0].bankId;
        }else if(this.form.paymentId === 7) {
          this.form.bankId = localBankList[0].bankId;
        }
      },
      getBankCode(bankId) {
        _.map(this.bankList, item => {
          if (item.bankId === bankId) {
            this.form.bankCode = item.bankCode;
          }
        });
      },
      
      //更新充值进度状态
      refreshStatus() {
        this.doGet({action: 'getStatus'});
      },
      
      doRechargeNow() {
        /**
         * 支付类型
         * 1.网银支付
         * 2.转账支付 [微信转账（需要附言），支付宝转账(需要扫码)，银行卡转账]
         * 3.快捷支付
         * 4.扫码支付
         */
        const {paymentId} = this.form;
        
        this.formError = '';
        
        this.$refs['form'].validate((valid) => {
          if (valid) {
            // switch (paymentId) {
            //   //银行卡转账
            //   case consts.PAY_BANKCARD_ZHUANZ:
            //     this.$_doRechargeTransfer();
            //     break;
            //   //支付宝转账
            //   case consts.PAY_ZHIFUBAO_ZHUANZ:
            //     if (this.innerPay) {
            //       this.$_doRechargeTransfer();
            //     } else {
            //       this.$_doBankPayment();
            //     }
            //     break;
            //   // 微信转账
            //   case consts.PAY_WEIXIN_ZHUANZ:
            //     // this.$_doWeixinTransfer();
            //     this.$_doRechargeTransfer();
            //     break;
            //   // 网银支付/快捷支付/银联扫码
            //   default:
            //     this.$_doBankPayment();
            // }
            if(this.innerPay){
              this.$_doRechargeTransfer();
            }else{
              this.$_doBankPayment();
            }
          }
        });
        // this.doSave({action:"saveForm",form:"form"});
      },
      
      $_doBankPayment() {
        const {token, uid} = getLogin();
        const urlStr = this.$_urlEncode({
          token,
          uid,
          'os-type': 0,
          'app-type': 2,
          'device-id': this.user.deviceId,
          ...this.form,
          'timestamp': moment().valueOf()
        }).substr(1);
        const $_window = window.open(`/api/gl/recharge/do/submit?${urlStr}`, '_blank');
        if ($_window) {
          this.btnLoading = true;
          setTimeout(() => {
            this.doAction({type: 'get', action: 'getStatus'});
          }, 2000);
        }
      },
      
      $_doWeixinTransfer() {
        this.fakeAmount = (this.form.amount - Math.random(0, 0.99)).toFixed(2);
        this.$confirm(`<p>系统对您的充值金额调整为<span>${this.fakeAmount}</span>元<br/>请支付<span>${this.fakeAmount}</span>元</p>`, '【为了避免支付限额】', {
          confirmButtonText: '去支付',
          cancelButtonText: '',
          dangerouslyUseHTMLString: true,
          showCancelButton: false,
          type: 'warning',
          center: true
        }).then(() => {
          this.$_doRechargeTransfer();
        }).catch(() => {
          // this.$message({
          //   type: 'info',
          //   message: '取消'
          // });
        });
      },
      
      $_doRechargeTransfer() {
        this.doSave({
          action: 'rechargeTransfer',
          form: 'form',
        });
      },
      
      $_urlEncode(param, key, encode) {
        if (param == null) return '';
        let paramStr = '';
        const t = typeof (param);
        if (t === 'string' || t === 'number' || t === 'boolean') {
          paramStr += '&' + key + '=' + ((encode == null || encode) ? encodeURIComponent(param) : param);
        } else {
          for (let i in param) {
            let k = key == null ? i : key + (param instanceof Array ? '[' + i + ']' : '.' + i);
            paramStr += this.$_urlEncode(param[i], k, encode);
          }
        }
        return paramStr;
      }
    },
    activated() {
      this.doGet({action: 'getFastAmountApi'});
    },
    
    mounted() {
      
      this.bindSave(rechargeTransfer, 'rechargeTransfer', 'form', {
        successMessage: '',
        beforeSend: (data) => {
          
          // if (data.paymentId === consts.PAY_WEIXIN_ZHUANZ) {
          //   data.amount = this.fakeAmount;
          // }
          
          this.formError = '';
          return data;
        },
        afterSuccess: ([result, data]) => {
          if (result) {
            this.doAction({type: 'get', action: 'getStatus'});
            // this.doAction({type: 'get', action: getRechargeList.name});
          } else {
            this.formError = data.message;
          }
        }
      });
      
      this.bindSave(getRechargePaymentInfoApi,'paymentInfo', 'form',{
        successMessage: '',
        beforeSend: (data) => {
          this.formError = '';
          return {
            amount: data.amount,
            limitType: data.limitType,
          };
        },
        afterSuccess: ([result, data]) => {
          this.btnLoading = false;
          if (result) {
            if(data && data.length > 0){
              window.localStorage.setItem('rechargeList', JSON.stringify(data));
              this.step = 2;
              this.rechargeList = data.filter((item) => {
                return _.find(consts.PAYMENT_LIST, {value: Number(item.paymentId)});
              });
              this.merchantList = this.rechargeList[0].merchantList;
              this.form.paymentId = this.rechargeList[0].paymentId;
              if(this.rechargeList[0].merchantList && this.rechargeList[0].merchantList.length >0){
                this.form.merchantAppId = this.rechargeList[0].merchantList[0].appId;
                if(this.rechargeList[0].merchantList[0].bankList.length > 0){
                  this.form.bankId = this.rechargeList[0].merchantList[0].bankList[0].bankId;
                }
                this.showlimitTip = this.rechargeList[0].merchantList[0].recommendStatus === 0 ? true : false;
              }
            }else{
              this.formError = '暂无可用支付方式！请从新输入充值金额';
            }
          } else {
            this.formError = '暂无可用支付方式！请从新输入充值金额';
          }
        },
        afterFail: ([result, data]) => {
          this.btnLoading = false;
          this.formError = data.message;
        }
      })
      
      this.bindGet(getRechargeFastAmount, 'fastAmount',{
        action: 'getFastAmountApi',
        format:(data) => {
          data.common = _.map(data.common,(val) => {return val > 5 ? val - _.random(1, 5) : val;});
          data.large = _.map(data.large,(val) => {return val > 5 ? val - _.random(1, 5) : val;});
          return data;
        },
        afterSuccess: ([result,data]) => {
          if(result){
            this.showMerchant = data.showMerchant;
            this.largeMerchant = data.largeMerchant;
          }
        }
      })
      
      this.bindGet(getRechargeStatus, 'rechargeStatus', {
        action: 'getStatus',
        format: data => {
          this.initForm();
          if (!_.isUndefined(data) && !_.isEmpty(data)) {
            const rechargeList = JSON.parse(window.localStorage.getItem('rechargeList'));
            if(rechargeList && !_.isUndefined(rechargeList)){
              _.map(rechargeList, item => {
                if (item.paymentId === data.paymentId) {
                  data.paymentName = item.paymentName;
                }
              });
            }else{
              data.paymentName = _.find(consts.PAYMENT_LIST, {value: data.paymentId}).title;
            }
          }
          return data;
        },
        afterSuccess:() => {
          this.btnLoading = false;
        }
      });
      this.getAll();
    },
  };
</script>

<style lang="scss">
  @include b(recharge) {
    width: 625px;
    margin: 0 auto;
    border-radius: $--border-radius-base;
    border:$--border-base;
    box-sizing: border-box;
    padding: 40px 50px;
    .el-form-item {
      margin-bottom: 15px;
    }
    .el-form--label-top .el-form-item__label {
      padding: 0;
    }

    .el-input {
      .el-input__prefix {
        .svg-icon {
          fill: rgba(0, 0, 0, .3);
        }
      }
    }

    @include e(tabs){
      display: flex;
      justify-content: center;
      border-bottom: 1px solid #DEDEDE;
      position: relative;
    }
    @include e(tabs-item){
      cursor: pointer;
      font-size: 14px;
      /*width: 150px;*/
      height: 30px;
      line-height: 20px;
      text-align: center;
      color: #999999;
      margin: 0 50px;
      font-weight: 700;
      &.active{
        color: #1E5ADC;
        border-bottom: 1px solid #1E5ADC;
      }
    }
    @include e(tabs-line){
      width: 1px;
      height: 23px;
      background: #DEDEDE;
    }

    @include e(center-amount){
      display: flex;
      margin-top: 30px;
    }

    @include e(amount) {
      .el-input__inner {
        box-shadow: none;
        &:hover,
        &:focus {
          border: none;
        }
      }
    }
    @include e(card_no) {
      display: block;
    }

    @include e(tip) {
      margin-top: 26px;
      border-top:1px solid #DEDEDE;
      display: flex;
      align-items: center;
      justify-content: center;
      color: $--color-info;
      padding-top: 15px;
      @include e(tip-faq){
        cursor: pointer;
        display: flex;
        align-items: center;
      }
      .svg-icon {
        margin-right: 10px;
      }
    }
  
    @include e(fee){
      position: relative;
      top: -10px;
      font-weight: bold;
      margin-bottom: 10px;
      &.fee-top{
        top: 10px;
      }
    }

    @include e(fee-block) {
      width: 200px;
      display: inline-block;
    }

    @include e(quick) {
      display: flex;
      justify-content: space-between;
      align-items: center;
      &:before,&:after{
        display: none;
      }
    }
    @include e(quick-group) {
      display: flex;
      flex-wrap: wrap;
      width: 440px;
      justify-content: flex-end;
    }

    @include e(quick-button) {
      width: 90px;
      min-width: auto;
      text-align: center;
      padding: 0;
      height: 38px;
      border-radius: 4px;
      margin-bottom: 10px;
      &:nth-child(n + 4){
       margin-bottom: 0px;
      }
    }

    @include e(next-btn){
      width: 100%;
      margin-top: 30px;
    }

    @include e(to-amount){
      display: inline-block;
      padding: 10px 15px;
      background: #1E5ADC;
      border: 2px solid #0C3DA5;
      border-radius: 4px;
      color: #ffffff;
      font-size: 14px;
      margin-top: 20px;
      font-weight: bold;
    }
    @include e(payment-option){
      display: flex;
      justify-content: space-between;
    }
  
    @include e(merchantAppId-limit){
      position: absolute;
      top: 5px;
      right: 20px;
    }
  }
  @include b(finance-modal) {
    @include e(bank-option) {
      height: 50px;
      line-height: 50px;
      display: flex;
      align-items: center;
      .bank-pic {
        margin-right: 10px;
      }
    }
    @include e(payment-option) {
      height: 50px;
      line-height: 50px;
      display: flex;
      align-items: center;
      .payment-pic {
        margin-right: 10px;
      }
    }
  }
</style>
